<?php

namespace app\api\controller;

use app\admin\model\Shoppingcart as ShoppingcartMdl;
use app\admin\model\Member;
use app\admin\model\Product;
use app\admin\model\Flashsale;
use app\admin\model\Buygifts;
use app\admin\model\Repurchase;

use think\Db;
use think\Exception;

/**
 * 购物车类
 */
class ShoppingCart extends Base
{

    /**
     * 更新购物车 加/减
     */
    public function updateCart()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->productId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品ID(productId) 不能为空');
        }
        if (empty($param->count) && $param->count != 0) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '数量(count) 不能为空');
        }
        if (empty($param->type) && $param->type != 0) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品类型(type) 不能为空');
        }

        $memberId = $param->memberId;
        $productId = $param->productId;
        $memberModel = new Member();
        $productModel = new Product();

        $member = $memberModel->get($memberId);
        if (!$member) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '当前会员不存在');
        }
        $product = $productModel->get($productId);
        if (!$product) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '当前商品不存在');
        }

        $shoppingcartModel = new ShoppingcartMdl();

        // TODO 是否已到限购数量


        // 当前用户购物车内商品
        $currentCartProduct = $shoppingcartModel->getCurrentCartProduct($productId, $memberId);
        // 检查库存
        $product['qty'] = Stock::getStock($product['id']);
        if($product['qty'] <= 0){
            return show(config('status.ERROR_STATUS'), '当前商品库存不足！计入失败。', "当前商品库存不足！计入失败。");
        }
        // 购买数量
        $data['count'] = $param->count;
        $data['product_id'] = $productId;
        // 是否是限时特价商品
        if ($param->type == 1) {
            $flashsaleInfo = Flashsale::where('product_id', $productId)->field('buy_limit_type, buy_limit_num')->find();
            // 限购数量
            if ($flashsaleInfo['buy_limit_type'] == 1) {
                $flashsale_limit_num = 1;
            } elseif ($flashsaleInfo['buy_limit_type'] == 2) {
                $flashsale_limit_num = 0;
            } else {
                $flashsale_limit_num = $flashsaleInfo['buy_limit_num'];
            }
        }
        // 是否是赠送商品
        if (isset($param->gift_product_id) && $param->gift_product_id) {
            $data['gift_product_id'] = $param->gift_product_id;
            /*if (empty($param->gift_count) && $param->gift_count != 0) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '赠送商品数量(gift_count) 不能为空');
            }
            // 赠送商品数量
            $data['gift_count'] = $param->gift_count;*/
            if (empty($param->buy_num)) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '购买数量(buy_num) 不能为空');
            }
            if (empty($param->gift_num)) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '赠送数量(gift_num) 不能为空');
            }
            $giftQty = Stock::getStock($param->gift_product_id);
            /*if($giftQty <= 0){
                return show(config('status.ERROR_STATUS'), '赠送商品库存不足！计入失败。', "赠送商品库存不足！计入失败。");
            }*/
        }
        // 是否是加价换购商品
        if (isset($param->is_repurchase) && $param->is_repurchase == 1) {
            /*if (empty($param->limit_num)) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '限购数量(limit_num) 不能为空');
            }*/
            // 限购数量
            $repurchase_limit_num = Repurchase::where('product_id', $productId)->value('limit_num');
            $data['is_repurchase'] = 1;
        }
        $data['member_id'] = $memberId;
        $data['status'] = $shoppingcartModel::STATUS_VALID; // 状态 有效

        if ($currentCartProduct && !empty($currentCartProduct)) {
            // 更新
            $data['id'] = $currentCartProduct->id;
            $data['update_date'] = date('Y-m-d H:i:s', time());
            $data['count'] = $param->count + $currentCartProduct->count;
            if ($data['count'] <= 0) {
                $data['status'] = $shoppingcartModel::STATUS_DELETE;
            }
            // 判断库存
            if($data['count'] > $product['qty']){
                return show(config('status.ERROR_STATUS'), '已超过当前商品库存！', '已超过当前商品库存！');
            }
            // 是否是限时特价商品
            if ($param->type == 1) {
                if ($flashsale_limit_num && $data['count'] > $flashsale_limit_num) {
                    return show(config('status.ERROR_STATUS'), '已超过当前商品的限购数量！', '已超过当前商品的限购数量！');
                }
            }
            // 赠送商品
            if (isset($param->gift_product_id) && $param->gift_product_id) {
                $baseNum = floor($data['count'] / $param->buy_num);
                // 赠送商品数量
                if ($baseNum > 0) {
                    $data['gift_count'] = $baseNum * $param->gift_num;
                } else {
                    $data['gift_count'] = 0;
                }
                // 赠送商品库存
                if ($data['gift_count'] > $giftQty) {
                    $data['gift_count'] = $giftQty;
                }
            }
            // 加价换购商品
            if (isset($param->is_repurchase) && $param->is_repurchase == 1) {
                if ($data['count'] > $repurchase_limit_num) {
                    return show(config('status.ERROR_STATUS'), '已超过当前商品的限购数量！', '已超过当前商品的限购数量！');
                }
            }

            $result = $shoppingcartModel->updateShoppingCart($data);
        } else {
            // 新增
            $data['create_date'] = date('Y-m-d H:i:s', time());
            if ($data['count'] <= 0) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '数量(count) 不能为0');
            }
            // 判断库存
            if($data['count'] > $product['qty']){
                return show(config('status.ERROR_STATUS'), '已超过当前商品库存！', '已超过当前商品库存！');
            }
            // 赠送商品
            if (isset($param->gift_product_id) && $param->gift_product_id) {
                $baseNum = floor($data['count'] / $param->buy_num);
                // 赠送商品数量
                if ($baseNum > 0) {
                    $data['gift_count'] = $baseNum * $param->gift_num;
                } else {
                    $data['gift_count'] = 0;
                }
                // 赠送商品库存
                if ($data['gift_count'] > $giftQty) {
                    $data['gift_count'] = $giftQty;
                }
            }
            // 加价换购商品
            if (isset($param->is_repurchase) && $param->is_repurchase == 1) {
                if ($data['count'] > $repurchase_limit_num) {
                    return show(config('status.ERROR_STATUS'), '已超过当前商品的限购数量！', '已超过当前商品的限购数量！');
                }
            }

            $result = $shoppingcartModel->updateShoppingCart($data);
        }

        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $shoppingcartModel->getError());
        }

        // 当前购物车信息
        $shoppingcartData = $shoppingcartModel->getCurrentCartInfo($memberId);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $shoppingcartData);
    }

    /**
     * 批量添加到购物车
     */
    public function addMultiToCart()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->multiProducts)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品集合(multiProducts) 不能为空');
        }
        if (!is_array($param->multiProducts)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品集合(multiProducts) 格式不正确');
        }

        $memberId = $param->memberId;
        $memberModel = new Member();
        $productModel = new Product();

        $member = $memberModel->get($memberId);
        if (!$member) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '当前会员不存在');
        }

        $shoppingcartModel = new ShoppingcartMdl();
        Db::startTrans();
        try {
            foreach ($param->multiProducts as $product) {
                $productId = $product['productId'];
                $product = $productModel->get($productId);
                if (!$product) {
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '商品'.$productId.'不存在');
                }

                // 检查库存
                $product['qty'] = Stock::getStock($product['id']);
                if($product['qty'] <= 0){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, "商品'.$productId.'库存不足！计入失败。");
                }
                // 购买数量
                $data['count'] = $product['count'];
                $data['product_id'] = $productId;
                $data['member_id'] = $memberId;
                $data['status'] = $shoppingcartModel::STATUS_VALID; // 状态 有效
                $data['create_date'] = date('Y-m-d H:i:s', time());
                if ($data['count'] <= 0) {
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '数量(count) 不能为0');
                }

                $result = $shoppingcartModel->updateShoppingCart($data);

                if ($result === false) {
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $shoppingcartModel->getError());
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '添加到购物车失败', $e->getMessage());
        }

        // 当前购物车信息
        $shoppingcartData = $shoppingcartModel->getCurrentCartInfo($memberId);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $shoppingcartData);
    }

    /**
     * 购物车列表
     */
    public function getList()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }

        $model = new ShoppingcartMdl();
        $where = [
            'a.status' => $model::STATUS_VALID,
            'a.member_id' => $param->memberId
        ];
        $fields = 'a.id, a.create_date, a.product_id, a.count, a.gift_product_id, a.gift_count, a.is_repurchase, p.name, p.img_url, p.price, p.unit, p.spec, p.describe, p.type, s.marketable as qty';
        $join = [
            ['__PRODUCT__ p', 'p.id = a.product_id'],
            ['__STOCK__ s', 's.product_id = a.product_id']
        ];
        $order = 'a.create_date DESC';
        $list = $model->alias('a')->where($where)->where(['p.status' => 1])->join($join)->field($fields)->order($order)->select();
        //$productModel = new Product();
        //$list = $productModel->formatProducts($list);
        $list = $this->formatProducts($list);
        // 失效商品
        $invalidList = $model->alias('a')->where($where)->where(['p.status' => 2])->join($join)->field($fields)->order($order)->select();
        $invalidList = $this->formatProducts($invalidList);

        $data = [
            'validList' => $list,
            'invalidList' => $invalidList
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 删除购物车商品
     */
    public function delete()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->cartIds)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '购物车ID(cartIds) 不能为空');
        }
        $cartIds = (array)$param->cartIds;
        $memberId = $param->memberId;

        $model = new ShoppingcartMdl();
        $result = $model->delAllShoppingCarts($cartIds, $memberId);

        if($result === false){
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
        }

        // 当前购物车信息
        $shoppingcartData = $model->getCurrentCartInfo($memberId);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $shoppingcartData);
    }

    /**
     * 处理商品格式
     */
    protected function formatProducts($products)
    {
        if ($products) {
            $unitArr = get_product_unit();
            foreach ($products as &$item) {
                $item['unit'] = $unitArr[$item['unit']];

                $productId = $item['product_id'];
                // 是否是活动商品 - 限时特价活动
                if ($item['type'] == 1) {
                    // 当前小时
                    $nowHour = date('G');
                    if ($nowHour >= 7 && $nowHour < 10) {
                        $time_range = 7;
                    } elseif ($nowHour >= 10 && $nowHour < 13) {
                        $time_range = 10;
                    } elseif ($nowHour >= 13 && $nowHour < 16) {
                        $time_range = 13;
                    } elseif ($nowHour >= 16 && $nowHour < 19) {
                        $time_range = 16;
                    } elseif ($nowHour >= 19 && $nowHour < 21) {
                        $time_range = 19;
                    } else {
                        $time_range = '';
                    }
                    if ($time_range) {
                        $flashsaleWhere = [
                            'product_id' => $productId,
                            'status' => 1,
                            'start_time' => ['elt', date('Y-m-d H:i:s')],
                            'end_time' => ['egt', date('Y-m-d H:i:s')],
                        ];
                        $flashsaleWhere['effective_date'] = ['like', '%,' . $time_range . ',%'];
                        $flashsaleInfo = Flashsale::where($flashsaleWhere)->field('promotion_type, promotion_discount, markup, buy_limit_type, buy_limit_num, start_time, end_time, effective_date, to_user_type, to_users, range, store_ids')->find();
                        if ($flashsaleInfo) {
                            $item['is_flashsale'] = 1; // 限时特价商品
                            $item['promotion_type'] = $flashsaleInfo['promotion_type'];
                            $item['promotion_discount'] = $flashsaleInfo['promotion_discount'];
                            $item['buy_limit_type'] = $flashsaleInfo['buy_limit_type'];
                            $item['buy_limit_num'] = $flashsaleInfo['buy_limit_num'];
                            // 优惠后的价格
                            $item['price'] = $flashsaleInfo['markup'];
                            // 限购数
                            if ($flashsaleInfo['buy_limit_type'] == 1) {
                                $item['limit_num'] = 1;
                            } elseif ($flashsaleInfo['buy_limit_type'] == 2) {
                                $item['limit_num'] = 0;
                            } else {
                                $item['limit_num'] = $flashsaleInfo['buy_limit_num'];
                            }

                            // 结束时间的时间戳
                            $endTime = strtotime(date('Y-m-d') . ' ' . ($time_range + 2) . ':59:59');
                            $item['endTime'] = $endTime;
                        } else {
                            $item['type'] = 0;
                        }
                    } else {
                        $item['type'] = 0;
                    }
                }

                // 是否是活动商品 - 买赠活动
                if ($item['type'] == 2) {
                    $buygiftInfo = Buygifts::where(['buy_product_id' => $productId, 'status' => 1])->field('gift_product_id, buy_num, gift_num, to_user_type, to_users, range, store_ids')->find();
                    if ($buygiftInfo) {
                        $item['gift_product_id'] = $buygiftInfo['gift_product_id'];
                        $item['buy_num'] = $buygiftInfo['buy_num'];
                        $item['gift_num'] = $buygiftInfo['gift_num'];
                        $item['to_user_type'] = $buygiftInfo['to_user_type'];
                        $item['to_users'] = $buygiftInfo['to_users'];
                        $item['to_users'] && $item['to_users'] = explode(',', $item['to_users']);
                        // 赠送商品
                        $item['gift_product_info'] = Product::where('id', $item['gift_product_id'])->field('name, price, unit')->find();
                        $item['gift_product_info']['unit'] = $unitArr[$item['gift_product_info']['unit']];
                    } else {
                        $item['type'] = 0;
                    }
                }

                // 是否是活动商品 - 加价换购
                if ($item['type'] == 3) {
                    // 限购数量
                    $repurchaseInfo = Repurchase::where(['product_id' => $productId, 'status' => 1])->field('markup, limit_num')->find();
                    if ($repurchaseInfo) {
                        $item['price'] = $repurchaseInfo['markup']; // 换购价
                        $item['limit_num'] = $repurchaseInfo['limit_num'];
                    }
                }
            }
        }

        return $products;
    }
}